﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using AMS.Web.UserControls;
using AMS.WorkBill.DataAccess;
using AMS.WorkBill.Entities;
using VitCode.BaseDataPageCreator;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Helper;
using VitCode.Castle.Management;

namespace AMS.Web.WorkBill
{
    public partial class BaseInfo : Page
    {
        private const string WO_STATE = "State";
        private readonly PermissionManager psManager = new PermissionManager();
        private PageBuilder m_PageBuilder;
        private WoPageBuilder m_WoPageBuilder;

        private string ClassName
        {
            get { return ReturnQueryStringValue("ClassName"); }
        }

        private string TypeName
        {
            get { return ReturnQueryStringValue("TypeName"); }
        }

        private string MenuId
        {
            get { return ReturnQueryStringValue("MenuId"); }
        }

        private string KeyFieldValue
        {
            get
            {
                if (ViewState["KeyFieldValue"] == null)
                    return "";
                return ViewState["KeyFieldValue"].ToString();
            }
            set { ViewState["KeyFieldValue"] = value; }
        }

        private static string SettingXmlPath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory + "Setting\\WoSetting.xml"; }
        }

        private string ReturnQueryStringValue(string keyString)
        {
            string strValue = Request.QueryString[keyString];
            if (strValue == null)
                strValue = "";
            return Convert.ToString(strValue);
        }

        private void SetData()
        {
            m_PageBuilder.SetPageData(ClassName, TypeName, m_WoPageBuilder.GetCurrSessionWoInfo(Page));
        }


        protected override void OnInit(EventArgs e)
        {
            if (m_PageBuilder == null)
                m_PageBuilder = new PageBuilder(this, SettingXmlPath);
            if (m_WoPageBuilder == null)
                m_WoPageBuilder = new WoPageBuilder(this, SettingXmlPath);
            ucNav.SettingXmlPath = SettingXmlPath;
            if (!string.IsNullOrEmpty(TypeName))
                m_PageBuilder.SetPageInfoContext(tblBaseInfo, ClassName, TypeName);
            else
                m_PageBuilder.SetPageInfoContext(tblBaseInfo, ClassName);
            ctlSelect.ClassName = ClassName;
            ctlSelect.TypeName = TypeName;
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(
                "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
            if (!IsPostBack)
            {
                m_WoPageBuilder.ClearCurrWoInfo(Page);
                string strKeyField = m_PageBuilder.GetPageKeyField(ClassName);
                KeyFieldValue = ReturnQueryStringValue(strKeyField);
                if (KeyFieldValue.Length > 0)
                    m_WoPageBuilder.SetCurrSessionWoInfo(Page, KeyFieldValue);
                SetPageTab("0");
                SetSessionCurrWoInfo();
                if (!psManager.CheckPageIsCanEdit(this))
                {
                    btnDraft.Enabled = false;
                    new CreateControlHelper().SetPageControlsDisabled(this);
                }
                
            }
            WorkBillInfo woInfo = m_WoPageBuilder.GetCurrSessionWoInfo(Page);
            if (m_WoPageBuilder.WoIsClose())
            {
                btnDraft.Enabled = false;
            }
            if (KeyFieldValue.Length == 0 && (woInfo == null || woInfo.Id == Guid.Empty))
                m_WoPageBuilder.SetCurrSessionWoInfo(Page, GetPageWoInfo());
            FileUpLoadCtl1.WoIdVal = m_WoPageBuilder.GetCurrSessionWoInfo(Page).Id.ToString();
        }

        private WorkBillInfo GetPageWoInfo()
        {
            var saveHelper = new PageSaveHelper(this, SettingXmlPath);
            var acc = new BaseDataAccess();
            object reVal = saveHelper.GetPageObject(ClassName, TypeName, KeyFieldValue, acc);
            if (reVal != null && reVal is WorkBillInfo)
                return ((WorkBillInfo) (reVal));
            return null;
        }

        private void SaveWoInfo()
        {
            var saveHelper = new PageSaveHelper(this, SettingXmlPath);
            object obj=null;
            StringCollection scMsg = new StringCollection();
            WorkBillAccess acc = new WorkBillAccess();
            WoRuleHelper ruleHelper = new WoRuleHelper();
            bool isAdd=false;
            acc.BeginTransaction();
            try
            {
                object pageObj = saveHelper.GetPageObject(ClassName, TypeName, KeyFieldValue, acc, out isAdd);
                if (pageObj == null || !(pageObj is WorkBillInfo))
                    throw new ArgumentException("保存的对象不是工单");
                WorkBillInfo woInfo = pageObj as WorkBillInfo;
                string strErrMsg = ruleHelper.CheckWoInfoSave(woInfo, TypeName);
                if (!string.IsNullOrEmpty(strErrMsg))
                    scMsg.Add(strErrMsg);
                else
                    obj = saveHelper.SavePageObject(woInfo, out scMsg, false, isAdd, acc);
                
                if (scMsg != null && scMsg.Count > 0)
                {
                    var sb = new StringBuilder();
                    for (int i = 0; i < scMsg.Count; i++)
                        sb.Append(scMsg[i] + "\r\n");
                    Alert.MessageBox(sb.ToString());
                }
                else if(obj != null)
                {
                    string strKeyField = m_PageBuilder.GetPageKeyField(ClassName);
                    PropertyInfo pi = obj.GetType().GetProperty(strKeyField);
                    KeyFieldValue = pi.GetValue(obj, null).ToString();
                    acc.Commit();
                    Alert.MessageBox("保存成功");
                    if (obj is WorkBillInfo)
                        m_WoPageBuilder.SetCurrSessionWoInfo(Page, (WorkBillInfo)obj);
                    SetData();
                }
            }
            catch(Exception ex)
            {
                acc.RollBack();
                throw ex;
            }
            finally
            {
                acc.CloseSession();
            }
            

            
        }

        protected void btnDraft_Click(object sender, EventArgs e)
        {
            var ctl = (EnumFromXmlCtl) FindControl(m_PageBuilder.m_LoadHelper.OBJ_PRO_HEAD_STRING + WO_STATE);
            ctl.SelectedValue = "Draft";
            SaveWoInfo();
        }

        private void SetSessionCurrWoInfo()
        {
            if (m_WoPageBuilder.GetCurrSessionWoInfo(Page) == null)
            {
                if (KeyFieldValue.Length == 0)
                    m_WoPageBuilder.SetCurrSessionWoInfo(Page, GetPageWoInfo());
                else
                    m_WoPageBuilder.SetCurrSessionWoInfo(Page, KeyFieldValue);
            }
        }

        private void SetPageTab(string selectedVal)
        {
            divBaseInfo.Visible = false;
            divSelectAsset.Visible = false;
            divSelectedAsset.Visible = false;
            divUpLoadFiles.Visible = false;
            if (selectedVal == "0")
            {
                divBaseInfo.Visible = true;
                SetData();
            }
            else if (selectedVal == "1")
            {
                ctlSelect.WoIdVal = m_WoPageBuilder.GetCurrSessionWoInfo(Page).Id.ToString();
                divSelectAsset.Visible = true;
            }
            else if (selectedVal == "2")
            {
                ctlSelected.WoIdVal = m_WoPageBuilder.GetCurrSessionWoInfo(Page).Id.ToString();
                ctlSelected.WoCode = m_WoPageBuilder.GetCurrSessionWoInfo(Page).Code;
                divSelectedAsset.Visible = true;
                ctlSelected.SetData();
                ctlImportor.Visible = !m_WoPageBuilder.WoIsClose();
            }
            else if (selectedVal == "3")
            {
                FileUpLoadCtl1.WoIdVal = m_WoPageBuilder.GetCurrSessionWoInfo(Page).Id.ToString();
                divUpLoadFiles.Visible = true;
            }
        }

        protected void pgMenu_MenuItemClick(object sender, MenuEventArgs e)
        {
            SetPageTab(e.Item.Value);
        }

        protected void btnCencel_Click(object sender, EventArgs e)
        {
            
            Response.Redirect("WoList.aspx?MenuId=" + MenuId + "&ClassName=" + ClassName + "&TypeName=" + TypeName);
        }
    }
}